package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.Employee;
import com.sky.entity.User;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.LoginFailedException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.EmployeeService;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.EmployeePageVO;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    // 小程序登录 ：https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/login.html
    // 微信服务接口地址 ：https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/code2Session.html
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 微信登录
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        //调用微信接口服务，获得当前微信用户的 openid
        Map<String, String> map = new HashMap<>();
        map.put("grant_type", "authorization_code");
        map.put("appid", weChatProperties.getAppid());
        map.put("js_code", userLoginDTO.getCode());
        map.put("secret", weChatProperties.getSecret());
        String json = HttpClientUtil.doGet(WX_LOGIN, map);

        String openid = ((JSONObject) JSONObject.parse(json)).getString("openid");
        //判断 openid 是否为空，如果为空表示登录失败，抛出业务异常
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //判断当前用户是否为新用户,如果 openid 在数据库表中已存在则为已注册用户，否则为新用户；目前只考虑为新用户的情况
        User userByOpenid = userMapper.getUserByOpenid(openid);
        //如果是新用户，自动完成注册
        User user = new User();
        if (userByOpenid == null) {
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            userMapper.save(user);
        }
        //返回这个用户对象
        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setOpenid(openid);
        userLoginVO.setId(user.getId());
        BaseContext.setCurrentId(user.getId());
        // 根据用户在系统中的唯一标识为微信用户生成jwt令牌
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), hashMap);
        userLoginVO.setToken(token);
        return userLoginVO;
    }
}
